import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import styles from '../StudentManagement.module.css';

const API_BASE = '/api';

interface Student {
  id: number;
  name: string;
  studentId: string;
  gender: string;
  birthDate: string;
  idCard: string;
  marketingDepartment: string;
  className: string;
  college: string;
  phone: string;
  dormBuilding: string;
  dormRoom: string;
  status: 'active' | 'suspended' | 'graduated';
  enrollmentDate: string;
  email?: string;
  guardianName?: string;
  guardianPhone?: string;
  guardianRelationship?: string;
}

interface StudentModalProps {
  student?: Student | null; // 编辑模式时传入的学生数据
  onSave: (data: Omit<Student, 'id'> | Student) => void;
  onClose: () => void;
}

// 验证手机号格式
const validatePhone = (phone: string) => {
  const phoneRegex = /^1[3-9]\d{9}$/;
  return phoneRegex.test(phone);
};

// 验证身份证号格式
const validateIdCard = (idCard: string) => {
  const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
  return idCardRegex.test(idCard);
};

const StudentModal = ({ student, onSave, onClose }: StudentModalProps) => {
  const { t } = useTranslation('student');
  const [formData, setFormData] = useState({
    name: '',
    studentId: '',
    gender: '男',
    birthDate: '',
    idCard: '',
    phone: '',
    email: '',
    marketingDepartment: '',
    college: '',
    className: '',
    dormBuilding: '',
    dormRoom: '',
    status: 'active' as 'active' | 'suspended' | 'graduated',
    enrollmentDate: '',
    guardianName: '',
    guardianPhone: '',
    guardianRelationship: ''
  });

  const [options, setOptions] = useState({
    marketingDepartments: [] as string[],
    colleges: [] as { id: number; name: string }[],
    classes: [] as { id: number; className: string; department: string }[], // 使用department字段而不是collegeId
    allClasses: [] as { id: number; className: string; department: string }[], // 保存所有班级用于筛选
    dormBuildings: [] as { id: number; name: string; genderType?: 'male' | 'female' }[],
    dormRooms: [] as { id: number; roomNumber: string; buildingId: number }[]
  });

  // 监护人关系选项，使用计算属性以确保语言切换时更新
  const guardianRelationships = [
    t('father'),
    t('mother'),
    t('grandfather'),
    t('grandmother'),
    t('maternalGrandfather'),
    t('maternalGrandmother'),
    t('other')
  ];

  const [errors, setErrors] = useState<{[key: string]: string}>({});
  const [errors, setErrors] = useState<{ [key: string]: string }>({});

  // 根据宿舍楼获取宿舍号
  const fetchRoomsByBuilding = async (buildingId: number) => {
    try {
      const response = await fetch(`${API_BASE}/dormitories/rooms?buildingId=${buildingId}`);
      const data = await response.json();
      
      // 获取学生的性别类型
      let studentGenderType: 'male' | 'female' | undefined;
      const gender = formData.gender || student?.gender;
      if (gender === '男' || gender === 'Male' || gender === 'male') {
        studentGenderType = 'male';
      } else if (gender === '女' || gender === 'Female' || gender === 'female') {
        studentGenderType = 'female';
      }
      
      // 过滤掉已满的宿舍（如果当前人数 >= 最大容量，则已满）
      const rooms = (data.data || [])
        .filter((room: any) => {
          // 如果学生已经在这个宿舍中，允许选择（允许修改床位）
          if (student && student.dormBuilding && student.dormRoom === room.roomNumber) {
            return true;
          }
          
          // 根据学生性别过滤宿舍：男生只能选择男生宿舍，女生只能选择女生宿舍
          if (studentGenderType && room.genderType) {
            if (room.genderType !== studentGenderType) {
              return false; // 性别不匹配，过滤掉
            }
          }
          
          // 过滤掉已满的宿舍
          return (room.currentCount || 0) < (room.maxCapacity || 0);
        })
        .map((room: any) => ({
          id: room.id,
          roomNumber: room.roomNumber,
          buildingId: room.buildingId,
          currentCount: room.currentCount,
          maxCapacity: room.maxCapacity,
          isFull: (room.currentCount || 0) >= (room.maxCapacity || 0)
        }));
      
      const rooms = (data.data || []).map((room: any) => ({
        id: room.id,
        roomNumber: room.roomNumber,
        buildingId: room.buildingId
      }));

      setOptions(prev => ({
        ...prev,
        dormRooms: rooms
      }));

      return rooms;
    } catch (error) {
      console.error('获取宿舍号失败:', error);
      return [];
    }
  };

  // 获取选项数据
  useEffect(() => {
    const fetchOptions = async () => {
      try {
        // 获取市场部选项（获取所有数据，不分页）
        const deptResponse = await fetch(`${API_BASE}/marketing?page=1&pageSize=1000`);
        const deptData = await deptResponse.json();
        const departments = (deptData.data || []).map((dept: any) => dept.name || dept);

        // 获取学院选项
        const collegeResponse = await fetch(`${API_BASE}/colleges`);
        const collegeData = await collegeResponse.json();
        const colleges = (collegeData.data || []).map((college: any) => ({
          id: college.id,
          name: college.name
        }));

        // 获取所有班级选项
        const classResponse = await fetch(`${API_BASE}/classes?page=1&pageSize=1000`);
        const classData = await classResponse.json();
        const allClasses = (classData.data || []).map((cls: any) => ({
          id: cls.id,
          className: cls.className,
          department: cls.department || '' // 使用department字段匹配学院
        }));

        // 获取宿舍楼选项
        const dormResponse = await fetch(`${API_BASE}/dormitories/buildings/all`);
        const dormData = await dormResponse.json();
        const dormBuildings = (dormData || []).map((building: any) => ({
          id: building.id,
          name: building.name,
          genderType: building.genderType // 包含性别类型
        }));

        setOptions(prev => ({
          ...prev,
          marketingDepartments: departments,
          colleges: colleges,
          allClasses: allClasses, // 保存所有班级
          classes: allClasses, // 初始显示所有班级
          dormBuildings: dormBuildings
        }));
      } catch (error) {
        console.error('获取选项数据失败:', error);
      }
    };

    fetchOptions();
  }, []);

  // 立即回显基本字段（不依赖选项数据）
  useEffect(() => {
    if (student) {
      setFormData(prev => ({
        ...prev,
        name: student.name || '',
        studentId: student.studentId || '',
        gender: student.gender || '男',
        birthDate: student.birthDate || '',
        idCard: student.idCard || '',
        phone: student.phone || '',
        email: (student as any).email ?? '',
        marketingDepartment: student.marketingDepartment || '',
        className: student.className || '',
        dormRoom: student.dormRoom || '',
        status: student.status || 'active',
        enrollmentDate: student.enrollmentDate || '',
        guardianName: (student as any).guardianName ?? '',
        guardianPhone: (student as any).guardianPhone ?? '',
        guardianRelationship: (student as any).guardianRelationship ?? ''
      }));
    }
  }, [student]);

  // 当选项数据加载完成后，回显依赖选项的字段（学院、宿舍楼）
  useEffect(() => {
    if (student && options.colleges.length > 0 && options.dormBuildings.length > 0 && options.allClasses.length > 0) {
      // 找到学院ID（通过名称匹配）
      const college = options.colleges.find(c => c.name === student.college);
      const collegeId = college ? college.id.toString() : '';

      // 根据学院筛选班级列表
      if (college) {
        const filteredClasses = options.allClasses.filter(cls =>
          cls.department === college.name
        );
        setOptions(prev => ({
          ...prev,
          classes: filteredClasses
        }));
      }

      // 找到宿舍楼ID（通过名称匹配）
      const building = options.dormBuildings.find(b => b.name === student.dormBuilding);
      const buildingId = building ? building.id.toString() : '';

      // 更新依赖选项的字段
      setFormData(prev => ({
        ...prev,
        college: collegeId,
        dormBuilding: buildingId
      }));

      // 加载宿舍号
      if (building) {
        const savedDormRoom = student.dormRoom || '';
        fetchRoomsByBuilding(building.id).then(() => {
          // 宿舍号加载完成后，确保dormRoom正确设置
          setFormData(prev => ({ ...prev, dormRoom: savedDormRoom }));
        });
      }
    }
  }, [student, options.colleges, options.dormBuildings, options.allClasses]);

  // 当宿舍号选项加载完成后，确保表单值正确设置
  useEffect(() => {
    if (student && formData.dormBuilding && formData.dormRoom === '' && options.dormRooms.length > 0) {
      // 查找匹配的宿舍号
      const matchedRoom = options.dormRooms.find(room => room.roomNumber === student.dormRoom);
      if (matchedRoom) {
        setFormData(prev => ({ ...prev, dormRoom: student.dormRoom || '' }));
      }
    }
  }, [options.dormRooms, student, formData.dormBuilding, formData.dormRoom]);

  const handleInputChange = (field: string, value: string) => {
    // 清除该字段的错误
    if (errors[field]) {
      setErrors(prev => ({ ...prev, [field]: '' }));
    }

    // 处理级联选择
    if (field === 'college') {
      // 根据选择的学院筛选班级
      const selectedCollege = options.colleges.find(c => c.id.toString() === value);
      if (selectedCollege) {
        // 根据学院名称筛选班级
        const filteredClasses = options.allClasses.filter(cls =>
          cls.department === selectedCollege.name
        );
        setOptions(prev => ({
          ...prev,
          classes: filteredClasses
        }));
        // 清空班级选择（因为学院变了）
        setFormData(prev => ({
          ...prev,
          [field]: value,
          className: '' // 清空班级选择
        }));
      } else {
        // 如果没有选择学院，显示所有班级
        setOptions(prev => ({
          ...prev,
          classes: prev.allClasses
        }));
        setFormData(prev => ({
          ...prev,
          [field]: value,
          className: ''
        }));
      }
      return; // 提前返回，避免重复设置
    }

    if (field === 'gender') {
      // 当性别改变时，如果已经选择了宿舍楼或宿舍，需要重新检查是否匹配
      // 如果性别不匹配，清空宿舍选择
      const buildingId = formData.dormBuilding ? parseInt(formData.dormBuilding) : null;
      if (buildingId && formData.dormBuilding) {
        // 检查当前选择的宿舍楼是否与新的性别匹配
        const selectedBuilding = options.dormBuildings.find(b => b.id === buildingId);
        let studentGenderType: 'male' | 'female' | undefined;
        if (value === '男' || value === 'Male' || value === 'male') {
          studentGenderType = 'male';
        } else if (value === '女' || value === 'Female' || value === 'female') {
          studentGenderType = 'female';
        }
        
        // 如果性别不匹配，清空宿舍楼和宿舍选择
        if (selectedBuilding && studentGenderType && selectedBuilding.genderType !== studentGenderType) {
          setFormData(prev => ({ ...prev, [field]: value, dormBuilding: '', dormRoom: '' }));
          setOptions(prev => ({ ...prev, dormRooms: [] }));
        } else {
          setFormData(prev => ({ ...prev, [field]: value }));
          // 如果匹配，重新加载宿舍房间
          if (buildingId) {
            fetchRoomsByBuilding(buildingId).catch(error => {
              console.error('加载宿舍号失败:', error);
            });
          }
        }
      } else {
        setFormData(prev => ({ ...prev, [field]: value }));
      }
      return; // 提前返回，避免重复设置
    }

    if (field === 'dormBuilding') {
      const buildingId = parseInt(value);
      if (buildingId) {
        setFormData(prev => ({ ...prev, [field]: value, dormRoom: '' }));
        fetchRoomsByBuilding(buildingId).catch(error => {
          console.error('加载宿舍号失败:', error);
        });
      } else {
        setOptions(prev => ({ ...prev, dormRooms: [] }));
        setFormData(prev => ({ ...prev, [field]: value, dormRoom: '' }));
      }
      return; // 提前返回，避免重复设置
    }

    // 普通字段更新
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const validateForm = () => {
    const newErrors: { [key: string]: string } = {};

    // 必填字段验证
    if (!formData.studentId.trim()) newErrors.studentId = t('studentIdRequired');
    if (!formData.name.trim()) newErrors.name = t('nameRequired');
    if (!formData.birthDate) newErrors.birthDate = t('birthDateRequired');
    if (!formData.idCard.trim()) newErrors.idCard = t('idCardRequired');
    if (!formData.phone.trim()) newErrors.phone = t('phoneRequired');
    if (!formData.email.trim()) newErrors.email = t('emailRequired');
    if (!formData.marketingDepartment) newErrors.marketingDepartment = t('marketingDepartmentRequired');
    if (!formData.college) newErrors.college = t('collegeRequired');
    if (!formData.className.trim()) newErrors.className = t('classNameRequired');
    if (!formData.dormBuilding) newErrors.dormBuilding = t('dormBuildingRequired');
    if (!formData.enrollmentDate) newErrors.enrollmentDate = t('enrollmentDateRequired');
    if (!formData.guardianName.trim()) newErrors.guardianName = t('guardianNameRequired');
    if (!formData.guardianPhone.trim()) newErrors.guardianPhone = t('guardianPhoneRequired');
    if (!formData.guardianRelationship) newErrors.guardianRelationship = t('guardianRelationshipRequired');

    // 格式验证
    if (formData.phone && !validatePhone(formData.phone)) {
      newErrors.phone = t('invalidPhoneFormat');
    }
    if (formData.idCard && !validateIdCard(formData.idCard)) {
      newErrors.idCard = t('invalidIdCardFormat');
    }
    if (formData.guardianPhone && !validatePhone(formData.guardianPhone)) {
      newErrors.guardianPhone = t('invalidGuardianPhoneFormat');
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    if (!validateForm()) {
      return;
    }

    // 将ID转换为名称
    const college = options.colleges.find(c => c.id.toString() === formData.college);
    const dormBuilding = options.dormBuildings.find(b => b.id.toString() === formData.dormBuilding);

    const submitData = {
      ...formData,
      college: college?.name || '',
      dormBuilding: dormBuilding?.name || ''
    };

    // 编辑模式下传递包含id的数据
    if (student?.id) {
      onSave({ ...submitData, id: student.id });
    } else {
      onSave(submitData);
    }
  };

  return (
    <div className={styles.modalOverlay}>
      <div className={`${styles.modal} ${styles.largeModal}`}>
        <div className={styles.modalHeader}>
          <h3>
            <span className={styles.modalIcon}>{student ? '✏️' : '➕'}</span>
            {student ? t('editStudent') : t('newStudent')}
          </h3>
          <button className={styles.closeBtn} onClick={onClose}>×</button>
        </div>

        <form onSubmit={handleSubmit} className={styles.studentForm}>
          {/* 基本信息 */}
          <div className={styles.formSection}>
            <h4 className={styles.formSectionTitle}>{t('basicInformation')}</h4>
            <div className={styles.formRow}>
              <div className={`${styles.formGroup} ${styles.required}`}>
                <label>{t('studentId')}</label>
                <input
                  type="text"
                  value={formData.studentId}
                  onChange={(e) => handleInputChange('studentId', e.target.value)}
                  placeholder={t('pleaseInputStudentId')}
                  className={errors.studentId ? styles.error : ''}
                />
                {errors.studentId && <div className={styles.errorText}>{errors.studentId}</div>}
              </div>
              <div className={`${styles.formGroup} ${styles.required}`}>
                <label>{t('name')}</label>
                <input
                  type="text"
                  value={formData.name}
                  onChange={(e) => handleInputChange('name', e.target.value)}
                  placeholder={t('pleaseInputName')}
                  className={errors.name ? styles.error : ''}
                />
                {errors.name && <div className={styles.errorText}>{errors.name}</div>}
              </div>
            </div>
            <div className={styles.formRow}>
              <div className={styles.formGroup}>
                <label>{t('gender')}</label>
                <select
                  value={formData.gender}
                  onChange={(e) => handleInputChange('gender', e.target.value)}
                >
                  <option value="男">{t('male')}</option>
                  <option value="女">{t('female')}</option>
                </select>
              </div>
              <div className={`${styles.formGroup} ${styles.required}`}>
                <label>{t('birthYearMonth')}</label>
                <input
                  type="date"
                  value={formData.birthDate}
                  onChange={(e) => handleInputChange('birthDate', e.target.value)}
                  className={errors.birthDate ? styles.error : ''}
                />
                {errors.birthDate && <div className={styles.errorText}>{errors.birthDate}</div>}
              </div>
            </div>
            <div className={styles.formRow}>
              <div className={`${styles.formGroup} ${styles.required}`}>
                <label>{t('idCard')}</label>
                <input
                  type="text"
                  value={formData.idCard}
                  onChange={(e) => {
                    const value = e.target.value.replace(/[^\dXx]/g, '');
                    if (value.length <= 18) {
                      handleInputChange('idCard', value);
                      
                      // 当身份证号长度为18位时，自动提取出生日期
                      if (value.length === 18) {
                        // 提取第7-14位作为出生日期（YYYYMMDD格式）
                        const birthDateStr = value.substring(6, 14);
                        // 验证日期格式
                        const year = birthDateStr.substring(0, 4);
                        const month = birthDateStr.substring(4, 6);
                        const day = birthDateStr.substring(6, 8);
                        
                        // 验证日期是否有效
                        const yearNum = parseInt(year);
                        const monthNum = parseInt(month);
                        const dayNum = parseInt(day);
                        
                        // 使用Date对象验证日期是否真正有效（避免2月30日等无效日期）
                        const testDate = new Date(yearNum, monthNum - 1, dayNum);
                        const isValidDate = testDate.getFullYear() === yearNum &&
                                          testDate.getMonth() === monthNum - 1 &&
                                          testDate.getDate() === dayNum;
                        
                        if (yearNum >= 1900 && yearNum <= 2100 && isValidDate) {
                          // 格式化为 YYYY-MM-DD
                          const formattedDate = `${year}-${month}-${day}`;
                          handleInputChange('birthDate', formattedDate);
                        }
                      } else if (value.length >= 14) {
                        // 如果身份证号还没输完但已经输入了完整的日期部分（14位），也可以提取
                        const birthDateStr = value.substring(6, 14);
                        if (birthDateStr.length === 8 && /^\d{8}$/.test(birthDateStr)) {
                          const year = birthDateStr.substring(0, 4);
                          const month = birthDateStr.substring(4, 6);
                          const day = birthDateStr.substring(6, 8);
                          
                          const yearNum = parseInt(year);
                          const monthNum = parseInt(month);
                          const dayNum = parseInt(day);
                          
                          const testDate = new Date(yearNum, monthNum - 1, dayNum);
                          const isValidDate = testDate.getFullYear() === yearNum &&
                                            testDate.getMonth() === monthNum - 1 &&
                                            testDate.getDate() === dayNum;
                          
                          if (yearNum >= 1900 && yearNum <= 2100 && isValidDate) {
                            const formattedDate = `${year}-${month}-${day}`;
                            handleInputChange('birthDate', formattedDate);
                          }
                        }
                      }
                    }
                  }}
                  placeholder={t('pleaseInputIdCardNumber')}
                  maxLength={18}
                  className={errors.idCard ? styles.error : ''}
                />
                {errors.idCard && <div className={styles.errorText}>{errors.idCard}</div>}
              </div>
            </div>
          </div>

          {/* 联系信息 */}
          <div className={styles.formSection}>
            <h4 className={styles.formSectionTitle}>{t('contactInformation')}</h4>
            <div className={styles.formRow}>
              <div className={`${styles.formGroup} ${styles.required}`}>
                <label>{t('phone')}</label>
                <input
                  type="tel"
                  value={formData.phone}
                  onChange={(e) => {
                    const value = e.target.value.replace(/\D/g, '');
                    if (value.length <= 11) {
                      handleInputChange('phone', value);
                    }
                  }}
                  placeholder={t('pleaseInputPhoneNumber')}
                  maxLength={11}
                  className={errors.phone ? styles.error : ''}
                />
                {errors.phone && <div className={styles.errorText}>{errors.phone}</div>}
              </div>
              <div className={`${styles.formGroup} ${styles.required}`}>
                <label>{t('email')}</label>
                <input
                  type="email"
                  value={formData.email}
                  onChange={(e) => handleInputChange('email', e.target.value)}
                  placeholder={t('pleaseInputEmail')}
                  className={errors.email ? styles.error : ''}
                />
                {errors.email && <div className={styles.errorText}>{errors.email}</div>}
              </div>
            </div>
          </div>

          {/* 组织信息 */}
          <div className={styles.formSection}>
            <h4 className={styles.formSectionTitle}>{t('organizationInformation')}</h4>
            <div className={styles.formRow}>
              <div className={`${styles.formGroup} ${styles.required}`}>
                <label>{t('marketingDepartment')}</label>
                <select
                  value={formData.marketingDepartment}
                  onChange={(e) => handleInputChange('marketingDepartment', e.target.value)}
                  className={errors.marketingDepartment ? styles.error : ''}
                >
                  <option value="">{t('pleaseSelectMarketingDepartment')}</option>
                  {options.marketingDepartments.map(dept => (
                    <option key={dept} value={dept}>{dept}</option>
                  ))}
                </select>
                {errors.marketingDepartment && <div className={styles.errorText}>{errors.marketingDepartment}</div>}
              </div>
              <div className={`${styles.formGroup} ${styles.required}`}>
                <label>{t('college')}</label>
                <select
                  value={formData.college}
                  onChange={(e) => handleInputChange('college', e.target.value)}
                  className={errors.college ? styles.error : ''}
                >
                  <option value="">{t('pleaseSelectCollege')}</option>
                  {options.colleges.map(college => (
                    <option key={college.id} value={college.id}>{college.name}</option>
                  ))}
                </select>
                {errors.college && <div className={styles.errorText}>{errors.college}</div>}
              </div>
            </div>
            <div className={styles.formRow}>
              <div className={`${styles.formGroup} ${styles.required}`}>
                <label>{t('className')}</label>
                <select
                  value={formData.className}
                  onChange={(e) => handleInputChange('className', e.target.value)}
                  disabled={!formData.college}
                  className={errors.className ? styles.error : ''}
                >
                  <option value="">
                    {formData.college ? t('pleaseSelectClass') : t('pleaseSelectCollegeFirst')}
                  </option>
                  {options.classes.map(cls => (
                    <option key={cls.id} value={cls.className}>
                      {cls.className}
                    </option>
                  ))}
                </select>
                {errors.className && <div className={styles.errorText}>{errors.className}</div>}
              </div>
              <div className={`${styles.formGroup} ${styles.required}`}>
                <label>{t('dormBuilding')}</label>
                <select
                  value={formData.dormBuilding}
                  onChange={(e) => handleInputChange('dormBuilding', e.target.value)}
                  className={errors.dormBuilding ? styles.error : ''}
                >
                  <option value="">{t('pleaseSelectDormBuilding')}</option>
                  {options.dormBuildings
                    .filter(building => {
                      // 根据学生性别过滤宿舍楼：男生只能选择男生宿舍楼，女生只能选择女生宿舍楼
                      const gender = formData.gender || student?.gender;
                      if (!gender || !building.genderType) {
                        return true; // 如果没有性别信息，显示所有宿舍楼
                      }
                      
                      let studentGenderType: 'male' | 'female' | undefined;
                      if (gender === '男' || gender === 'Male' || gender === 'male') {
                        studentGenderType = 'male';
                      } else if (gender === '女' || gender === 'Female' || gender === 'female') {
                        studentGenderType = 'female';
                      }
                      
                      // 如果学生已经在某个宿舍楼中，允许选择（即使性别不匹配）
                      if (student && student.dormBuilding === building.name) {
                        return true;
                      }
                      
                      // 性别匹配才显示
                      return studentGenderType === building.genderType;
                    })
                    .map(building => (
                      <option key={building.id} value={building.id}>{building.name}</option>
                    ))}
                </select>
                {errors.dormBuilding && <div className={styles.errorText}>{errors.dormBuilding}</div>}
              </div>
            </div>
            <div className={styles.formRow}>
              <div className={styles.formGroup}>
                <label>{t('dormRoom')}</label>
                <select
                  value={formData.dormRoom}
                  onChange={(e) => handleInputChange('dormRoom', e.target.value)}
                  disabled={!formData.dormBuilding}
                >
                  <option value="">{formData.dormBuilding ? t('pleaseSelectDormRoom') : t('pleaseSelectBuildingFirst')}</option>
                  {options.dormRooms.map(room => {
                    const isCurrentRoom = student && student.dormRoom === room.roomNumber;
                    const isFull = !isCurrentRoom && (room.currentCount || 0) >= (room.maxCapacity || 0);
                    return (
                      <option 
                        key={room.id} 
                        value={room.roomNumber}
                        disabled={isFull}
                      >
                        {room.roomNumber}{isFull ? ' (已满)' : ` (${room.currentCount || 0}/${room.maxCapacity || 0})`}
                      </option>
                    );
                  })}
                </select>
              </div>
              <div className={styles.formGroup}>
                <label>{t('status')}</label>
                <select
                  value={formData.status}
                  onChange={(e) => handleInputChange('status', e.target.value)}
                >
                  <option value="active">{t('active')}</option>
                  <option value="suspended">{t('onLeave')}</option>
                  <option value="graduated">{t('graduated')}</option>
                </select>
              </div>
            </div>
          </div>

          {/* 监护人信息 */}
          <div className={styles.formSection}>
            <h4 className={styles.formSectionTitle}>{t('guardianInformation')}</h4>
            <div className={styles.formRow}>
              <div className={`${styles.formGroup} ${styles.required}`}>
                <label>{t('guardianName')}</label>
                <input
                  type="text"
                  value={formData.guardianName}
                  onChange={(e) => handleInputChange('guardianName', e.target.value)}
                  placeholder={t('pleaseInputGuardianName')}
                  className={errors.guardianName ? styles.error : ''}
                />
                {errors.guardianName && <div className={styles.errorText}>{errors.guardianName}</div>}
              </div>
              <div className={`${styles.formGroup} ${styles.required}`}>
                <label>{t('guardianPhone')}</label>
                <input
                  type="tel"
                  value={formData.guardianPhone}
                  onChange={(e) => {
                    const value = e.target.value.replace(/\D/g, '');
                    if (value.length <= 11) {
                      handleInputChange('guardianPhone', value);
                    }
                  }}
                  placeholder={t('pleaseInputGuardianPhone')}
                  maxLength={11}
                  className={errors.guardianPhone ? styles.error : ''}
                />
                {errors.guardianPhone && <div className={styles.errorText}>{errors.guardianPhone}</div>}
              </div>
            </div>
            <div className={styles.formRow}>
              <div className={`${styles.formGroup} ${styles.required}`}>
                <label>{t('guardianRelationship')}</label>
                <select
                  value={formData.guardianRelationship}
                  onChange={(e) => handleInputChange('guardianRelationship', e.target.value)}
                  className={errors.guardianRelationship ? styles.error : ''}
                >
                  <option value="">{t('pleaseSelectRelationship')}</option>
                  {guardianRelationships.map(relation => (
                    <option key={relation} value={relation}>{relation}</option>
                  ))}
                </select>
                {errors.guardianRelationship && <div className={styles.errorText}>{errors.guardianRelationship}</div>}
              </div>
            </div>
          </div>

          {/* 时间信息 */}
          <div className={styles.formSection}>
            <h4 className={styles.formSectionTitle}>{t('timeInformation')}</h4>
            <div className={styles.formRow}>
              <div className={`${styles.formGroup} ${styles.required}`}>
                <label>{t('enrollmentDate')}</label>
                <input
                  type="date"
                  value={formData.enrollmentDate}
                  onChange={(e) => handleInputChange('enrollmentDate', e.target.value)}
                  className={errors.enrollmentDate ? styles.error : ''}
                />
                {errors.enrollmentDate && <div className={styles.errorText}>{errors.enrollmentDate}</div>}
              </div>
            </div>
          </div>

          <div className={styles.modalActions}>
            <button type="button" className={styles.btnCancel} onClick={onClose}>
              {t('common:cancel')}
            </button>
            <button type="submit" className={styles.btnPrimary}>
              {student ? t('common:save') : t('addStudent')}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default StudentModal;
